import React, { Component } from "react";
import { getToken } from "@utils/token.js";
import { Dialog, SwipeAction, Toast, Checkbox, Stepper, Button } from "antd-mobile";
import { LeftOutline } from "antd-mobile-icons";
import { store } from '../../store/index'
import MyTabbar from "../../components/MyTabbar";
import { cartList, setGoodsNum, setGoodsSelect, delGoods } from "@api";
import "./index.scss";

export default class Cart extends Component {
  state = {
    cartList: [],
    allNum: 0,
    allPrice: 0,
    allcheck: true,
    keys: [],
    hasItem: true,
    setOrOver: true
  };
  render() {
    return (
      <div className="sc_cart">
        <div className="item-head">
          <div className="goback">
            <LeftOutline />
          </div>
          <div className="title">购物车</div>
          <div className="gopage" onClick={this.setItem}>
            {
              this.state.setOrOver ? '管理' : '完成'
            }
          </div>
        </div>
        <div className="sc_citem">
          <ul>
            {this.state.cartList.length !== 0 ?
              this.state.cartList.map((item) => (
                <li key={item.key}>
                  <SwipeAction rightActions={[{ key: "delete", text: "删除", color: "danger", onClick: (value) => { this.delGoods(value, item.key) } }]} >
                    <div className="item_box">
                      <div className="itemcheck clearfix">
                        <Checkbox checked={item.selected} onChange={(value) => this.setGoodsSelect(value, item.key)} />
                      </div>
                      <div className="iteminfo">
                        <div className="item_img">
                          <img src={item.pic} alt={item.name} />
                        </div>
                        <div className="item_msg">
                          <div className="msg_name">{item.name}</div>
                          <div className="msg_price">¥{item.price}</div>
                        </div>
                        <div className="item_step">
                          <Stepper min={0} defaultValue={item.number} onChange={(value) => this.setGoodsNum(value, item.key)} />
                        </div>
                      </div>
                    </div>
                  </SwipeAction>
                </li>
              ))
              :
              <img src='https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Fb209937dc2276a7cb5a47fb831879af25c52fa1b25567-NGX9jR_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1643854399&t=38b125f8e1cfb1e6206009fd86f762df' className='nullimg' alt='nullimg' />
            }
          </ul>
        </div>
        <div className="postorder clearfix">
          <div className="allcheck">
            <Checkbox checked={this.state.allcheck} onChange={(value) => this.setAllSelect(value)} /><span>全选</span>
          </div>
          <div className="del">
            {
              this.state.cartList ?
                this.state.setOrOver ? '' : <Button color='danger' onClick={this.delSelect}>删除</Button>
                :
                ''
            }
          </div>
          <div className="orderbutton"><Button color='danger'>提交订单</Button></div>
          <div className="price">¥ {this.state.allPrice}</div>
        </div>
        <MyTabbar pathname={this.props.match.path} allNum={this.state.allNum} ></MyTabbar>
      </div>
    );
  }
  componentDidMount() {
    this.cartList();
    // redux改变触发
    store.subscribe(() => {
      // 触发render（）
      this.setState({})
    })
  }
  componentWillUnmount() {
    this.setState = () => false;
  }
  // 管理/完成
  setItem = () => {
    this.setState({
      setOrOver: !this.state.setOrOver
    })
  }
  // 获取购物车列表
  cartList = async () => {
    await cartList({
      token: getToken(),
    }).then((res) => {
      console.log(res);
      if (res.data.code === 0) {
        this.setState({
          cartList: res.data.data.items,
          allPrice: res.data.data.price
        })
        store.dispatch({ type: 'allnumber', data: Number(res.data.data.number) })
      }
      if (res.data.code === 700) {
        this.setState({
          cartList: [],
        })
        store.dispatch({ type: 'allnumber', data: 0 })
        return false
      }
      this.setState({
        allcheck: this.state.cartList.every((item) => item.selected)
      })
    })
  }
  // 数量+ -
  setGoodsNum = async (value, key) => {
    if (value <= 0) {
      this.delGoods(value, key)
    } else if (value > 0) {
      console.log(value, key);
      await setGoodsNum({
        key,
        number: value,
        token: getToken(),
      }).then((res) => {
        this.setState({
          cartList: res.data.data.items,
          allPrice: res.data.data.price
        })
        this.cartList();
      })
    }
  };
  // 改变单个选中状态
  setGoodsSelect = async (value, key) => {
    await setGoodsSelect({
      key,
      selected: value,
      token: getToken(),
    }).then(async (res) => {
      if (res.data.code === 0) {
        await this.setState({
          cartList: res.data.data.items,
          allPrice: res.data.data.price,
        })
      }
    })
    this.setState({
      allcheck: this.state.cartList.every((item) => item.selected)
    })
  };
  // 全选按钮改变状态
  setAllSelect = (value) => {
    console.log(this.state.cartList);
    if (this.state.cartList.length === 0) {
      this.setState({
        allcheck: !this.state.allcheck,
      })
      return false
    }
    let keys = []
    this.state.cartList.forEach((item) => {
      keys.push(item.key)
    })
    keys = keys.join(',')
    setGoodsSelect({
      key: keys,
      selected: value,
      token: getToken(),
    }).then((res) => {
      console.log(res);
      if (res.data.code === 0) {
        this.setState({
          allcheck: !this.state.allcheck,
          cartList: res.data.data.items,
          allPrice: res.data.data.price
        })
        store.dispatch({ type: 'allnumber', data: Number(res.data.data.number) })
      }
    })
  }
  // 删除单个
  delGoods = (value, key) => {
    Dialog.confirm({
      content: '是否删除？',
      onConfirm: () => {
        delGoods({
          key,
          token: getToken()
        }).then((res) => {
          if (res.data.code === 0) {
            this.cartList()
            Toast.show({
              icon: 'success',
              content: '删除成功'
            })
          }
          if (res.data.code === 700) {
            this.setState({
              cartList: [],
              allPrice: 0,
              setOrOver: true
            })
            this.cartList();
          }
        })
      },
      onCancel: () => {
        this.props.history.go(0)
      }
    })
  }
  // 删除选中
  delSelect = () => {
    const checkedGoods = this.state.cartList.filter((item) => item.selected)
    const keys = []
    for (var i = 0; i < checkedGoods.length; i++) {
      keys.push(checkedGoods[i].key)
    }
    if (keys.length === 0) {
      Toast.show({
        icon: 'fail',
        content: '什么也没有选中'
      })
      return false
    }
    Dialog.confirm({
      content: '是否删除？',
      onConfirm: () => {
        delGoods({
          key: keys.join(','),
          token: getToken()
        }).then((res) => {
          console.log(res);
          if (res.data.code === 0) {
            Toast.show({
              icon: 'success',
              content: '删除成功'
            })
            this.cartList()
          }
          if (res.data.code === 700) {
            this.setState({
              cartList: [],
              allPrice: 0,
              setOrOver: true
            })
            this.cartList();
          }
        })
      }
    })
  }
}
